import {$common,$http,validate,checkNetWork,startNativeVerify,nativeVerify,compareVersion,reportError, Log,extend} from './index';
import { defaultConfig } from './constant';

var init = function (config) {
  // Monitor network
  wx.onNetworkStatusChange(function (res) {
    if (res.networkType === 'none' || res.networkType === '2g') {
      uni.showToast({
        title: '网络异常',
        icon: 'none'
      })
    }
  })

  // Monitor memory
  uni.onMemoryWarning( () => {
    reportError(Log.memoryWarn)
  })

  // 根据初始化传值，决定URL
  if (!uni.faceidVerifySdkBaseUrl) {
    $common.setBaseUrl()
  }
  /**
   * Start Verify
   */
  uni.startVerify = function (obj) {
    console.log('startVerify start, send data', getCurrentPages()[0].$page.fullPath)
    $common.setInit()
    // Data validate
    if (!obj.data || !obj.fail || !obj.success) {
      console.log('调用SDK失败，wx.startVerify传入参数缺少！')
      var err = {
        ErrorCode: -100,
        ErrorMsg: '调用SDK失败，wx.startVerify传入参数缺少！'
      }
      uni.showModal({
        title: '提示',
        content: err.ErrorMsg,
        showCancel: false
      })
      return
    }
    // 如果end_path 有值
    if (obj.data.endPath) {
      if (!validate(obj.data.endPath, 'end_path')) {
        var err = {
          ErrorCode: -100,
          ErrorMsg: '调用SDK失败，endPath格式错误！'
        }
        uni.showModal({
          title: '提示',
          content: err.ErrorMsg,
          showCancel: false
        })
        return
      }

      // 验证失败时，navigate到下一页
      obj.fail = function (data) {
        if (data.error_code === -999) {
          wx.navigateBack()
          return
        }
        var tempURL = ''
        if (obj.data.endPath.indexOf('?') >= 0) {
          tempURL = obj.data.endPath + '&data=' + encodeURIComponent(JSON.stringify(data))
        } else {
          tempURL = obj.data.endPath + '?data=' + encodeURIComponent(JSON.stringify(data))
          // tempURL = obj.data.endPath + "";
        }
        console.log(tempURL)
        wx.navigateTo({
          url: tempURL,
          fail: err => {
            console.log(err)
            uni.showModal({
              title: '提示',
              content: err.errMsg,
              showCancel: false
            })
          }
        })
      }
      // 验证成功如果会关闭当前页，跳转到下一页，如果原生隐藏了首页会关闭客户的一个页面
      obj.success = function (data) {
        var tempURL = ''
        if (obj.data.endPath.indexOf('?') >= 0) {
          tempURL = obj.data.endPath + '&data=' + JSON.stringify(data)
        } else {
          tempURL = obj.data.endPath + '?data=' + JSON.stringify(data)
        }
        console.log('obj.success tempURL',tempURL)
        uni.redirectTo({
          url: tempURL,
          fail: err => {
            console.log(err)
            uni.showModal({
              title: '提示',
              content: err.errMsg,
              showCancel: false
            })
          }
        })
      }
    }
    uni.verifySuccessFunc = res => {
      console.log('verifySuccessFunc')
      obj.success(res);
      // 核验完成后取消内存告警
      uni.offMemoryWarning();
    }
    uni.verifyFailureFunc = res => {
      console.log('verifyFailureFunc')
      obj.fail(res);
      // 核验完成后取消内存告警
      uni.offMemoryWarning();
    }
    $common.setBizdata(obj.data);



    if (!validate(obj.data.token, 'token')) {
      // obj.fail({ErrorCode: -102, ErrorMsg: "调用SDK失败,token格式错误！"});
      uni.showModal({
        title: '提示',
        content: '调用SDK失败,token格式错误！',
        showCancel: false
      })
      return
    }
    $common.setToken(obj.data.token);

    uni.showLoading({
      title: '加载中...',
      mask: true
    })
    // Get cmsConfig
    getCmsConfig(obj.data.token, function (res) {
      console.log('getCmsConfig',res)
      uni.hideLoading()
      // 如果 getConfig 失败
      if (res.ErrorCode !== 0) {
        // obj.fail(res);
        uni.showModal({
          title: '提示',
          content: res.ErrorMsg,
          showCancel: false
        })
        return
      }

      // 将getConfig配置覆盖到defaultConfig

      extend(true, defaultConfig, res.Data.config)
      // 将合并生成的配置
      var cmsConfig = defaultConfig

      wx.verifySysInfo = wx.getSystemInfoSync()
      var limitVer =
        wx.verifySysInfo.platform === 'ios'
          ? cmsConfig.JustForMp.iOSVerLimit
          : cmsConfig.JustForMp.androidVerLimit
      // limitVer is not null and limit version is equal or greater than wechat version
      if (
        wx.verifySysInfo.platform !== 'devtools' &&
        limitVer &&
        compareVersion(limitVer, wx.verifySysInfo.version) > 0
      ) {
        uni.hideLoading()
        uni.showModal({
          title: '提示',
          content: `当前微信版本低于${limitVer}，无法使用该功能，请升级到最新微信版本后重试。`,
          showCancel: false
        })
        return
      }

      //企业微信检查
      if (wx.verifySysInfo.environment && wx.verifySysInfo.environment === 'wxwork') {
        uni.showModal({
          title: '提示',
          content: `企业微信暂不支持使用此功能，请使用微信进行操作`,
          showCancel: false
        })
        return false
      }

      cmsConfig.intentionVerifyText = res.Data.intentionVerifyText
      cmsConfig.endPath = obj.data.endPath;

      // Cms config  revise
      cmsConfig = reviseCmsConfig('', cmsConfig)
      $common.setCmsConfig(cmsConfig)
      $common.setNavTitle(cmsConfig.navTitle)
      console.log('reviseCmsConfig cmsConfig=>', cmsConfig)

      // 如果是原生, 且无OCR, 且去掉首页，直接调用微信原生接口
      if (
        cmsConfig.Common.IsWxNative &&
        !cmsConfig.Common.Flow.includes('Ocr') && !cmsConfig.Common.Flow.includes('IntentionVerify')
        && cmsConfig.Common.IsHideIndexWhenNative
      ) {
        console.log('直接调用微信原生接口')
        let WxVerifyTypeIsVideo = cmsConfig.Common.WxVerifyTypeIsVideo
        let tempWxCheckAliveType = cmsConfig.Common.WxCheckAliveType
        nativeVerify(
          WxVerifyTypeIsVideo,
          tempWxCheckAliveType,
          uni.faceidVerifySdkBaseUrl,
          obj.data.token,
          uni.verifyFailureFunc,
          res => {
            let tempRes = {
              BizToken: obj.data.token,
              ErrorCode: res.ErrorCode,
              ErrorMsg: res.ErrorMsg,
            }
            if (res.ErrorCode === 0) {
              // 验证成功
              uni.verifySuccessFunc(tempRes)
            } else {
              // 验证失败
              uni.verifyFailureFunc(tempRes)
            }
          }
        )
        return
      }
      console.log('进入验证页面',cmsConfig)
      nextPage(cmsConfig, obj.data.startPath)
    })
  }
}

var nextPage = async function (cmsConfig, startPath) {
  if (startPath) {
    uni.navigateTo({
      url: startPath
    })
  } else {
    if (cmsConfig.IsHideIndexAlways) {
      checkNetWork(() => {
        // 如果是原生接口,且没有OCR
        if (
          cmsConfig.Common.IsWxNative &&
          !cmsConfig.Common.Flow.includes("Ocr")
        ) {
          startNativeVerify(cmsConfig);
          return;
        }
        var nextPage = "sms";
        if (cmsConfig.isHideSmsPage) {
          if (cmsConfig.isHideOcrPage) {
            nextPage = "verifyLivingBody";
          } else {
            nextPage = "ocr";
          }
        }
        console.log("nextPage", nextPage);
        $common.setCurPage({url:nextPage});
      });
    } else {
      $common.setCurPage({url:'protocol'})
    }

  }
}
/**
 * Get cmsConfig
 */
var getCmsConfig = async function (token, callback) {
  $http(
    {
      url: `/api/auth/getConfig?BizToken=${token}`,
      method: "POST",
      reTry: {
        tryCount: 5
      }
    },
    res => {
      console.log("getToken error", res);
      if (res.ErrorCode === 0) {
        callback({ ErrorCode: 0, Data: res.Data })
      } else {
        if (res.ErrorCode) {
          callback({
            ErrorCode: res.ErrorCode,
            ErrorMsg: `获取配置失败,${res.ErrorMsg}`
          })
        } else {
          callback({ ErrorCode: -104, ErrorMsg: `调用失败，获取配置异常！` })
        }
        reportError(Log.getCmsConfigErr,res,{urL: uni.faceidVerifySdkBaseUrl})
      }
    }
  );
};


/**
 * Revise cmsConfig, because of that cmsConfig has some special control when some setting
 * Such as if send the token argument, need go skip sms and ocr logic, So it must edit the cmsConifg
 * @data data.token
 * 将H5的配置应用到小程序上面, 注意：反转后的配置，除了Common，其他和正式的都会有一些区别
 */
var reviseCmsConfig = function (data, cmsConfig) {
  let flow = cmsConfig.Common.Flow
  let intentionVerifyText = cmsConfig.intentionVerifyText
  let isHideSmsPage = false
  let isHideOcrPage = false
  let isHideAsrPage = false
  let isJustOcr = false
  let isJustSms = false
  let livingbodyType = 0
  let isHaveLive =
    flow.indexOf('LiveFour1V1') >= 0 ||
    flow.indexOf('LiveAction1V1') >= 0 ||
    flow.indexOf('LiveSilence1V1') >= 0
  if (flow.indexOf('Sms') === -1) {
    // 如果不包含Sms
    isHideSmsPage = true
  }
  if (flow.indexOf('Ocr') === -1) {
    // 如果不包含Ocr
    isHideOcrPage = true
  }
  // 如果不包含Asr,或者语音没有默认文案都不走意愿核身
  if (flow.indexOf('IntentionVerify') === -1 || !intentionVerifyText) {
    isHideAsrPage = true
  }
  if (isHaveLive) {
    // 设置活体类型
    if (flow.indexOf('LiveFour1V1') >= 0) {
      livingbodyType = 0
    } else if (flow.indexOf('LiveAction1V1') >= 0) {
      livingbodyType = 1
    } else {
      livingbodyType = 2
    }
  }
  // 仅Ocr的情况 (没活体且没Sms)
  if (!isHaveLive && flow.indexOf('Sms') === -1) {
    isJustOcr = true
  }
  // 仅Sms的情况 (没活体且没Ocr)
  if (!isHaveLive && flow.indexOf('Ocr') === -1) {
    isJustSms = true
  }
  const  navTitle =  {
    smsTitle: cmsConfig.Common.NavTitle.SmsTitle,
    ocrTitle: cmsConfig.Common.NavTitle.OcrTitle,
    livingbodyTitle: cmsConfig.Common.NavTitle.LivingbodyTitle,
    resultTitle: cmsConfig.Common.NavTitle.ResultTitle,
    asrTitle: cmsConfig.Common.NavTitle.asrTitle,
  }

  let config = {
    Common: {
      ...cmsConfig.Common,
      endPath:cmsConfig.endPath,
    },
    protocol: {
      title: cmsConfig.Index.ProtocolTitle,
      content: cmsConfig.Index.TencentProtocol,
      clientContent: cmsConfig.Index.ClientProtocol
    },
    page: {
      index: {
        clientName: cmsConfig.Index.ProjectName,
        businessName: cmsConfig.Index.BusinessName,
        certificationCenter: cmsConfig.Index.CooperationName,
        nextBtnName: cmsConfig.Index.NextBtn,
        isHideTipsAbout: cmsConfig.Common.IsHideAbout,
        protocolTitle: cmsConfig.Index.ProtocolEntrance,
        authorizedProtocol: cmsConfig.Index.AuthorizedProtocol,
      },
      ocr: {
        backend: cmsConfig.Ocr.Backend,
        sourceType: cmsConfig.Ocr.SourceType,
        isAddress: cmsConfig.Ocr.IsAddress,
        isManualInput: cmsConfig.Ocr.IsManualInput,
        isHideTakePhoto: cmsConfig.Ocr.IsHideManualInputTakePhotoBtn,
        isCheckIDInfo: cmsConfig.Ocr.IsCheckIdInfo,
        allowModifyType: cmsConfig.Ocr.AllowModifyType // H5与小程序相反 1 不可修改 0 可修改，需要反转
      },
      livingbody: {
        silentRecordTime: cmsConfig.LiveFour1V1.MaxDuration
      },
      success: {
        successTitle: cmsConfig.Success.SubTipsName,
        successTips: cmsConfig.Success.SuccessTips,
        isAutoSkip: cmsConfig.Success.AutoSkip
      },
      sms: {},
      failpage: {
        isShowExitBtn: cmsConfig.Fail.IsShowQuitBtn,
        exitBtnTtile: cmsConfig.Fail.ExitBtnText,
        RetryBtnText: cmsConfig.Fail.RetryBtnText
      }
    },
    runEnv: 'release',
    navTitle,
    justForJumpVer: {
      title: cmsConfig.Common.Title
    },
    about: {
      title: '关于腾讯云慧眼',
      content: '腾讯云慧眼由腾讯AI Lab、腾讯优图、腾讯数据平台部提供技术支持。'
    },
    isGetUserLocation: cmsConfig.Index.IsGetLocation,
    IsHideIndexAlways: cmsConfig.Common.IsHideIndexAlways,
    isHideSmsPage,
    isHideOcrPage,
    isHideAsrPage,
    livingbodyType,
    isJustOcr,
    isJustSms,
    failInfo: cmsConfig.Fail.CustomFailInfo,
    // Setting the skip config， 用作导航
    skipConfig:{
      isHideSmsPage: isHideSmsPage,
      isHideOcrPage: isHideOcrPage,
      isHideAsrPage: isHideAsrPage,
      isJustSms: isJustSms,
      isJustOcr: isJustOcr,
      navTitle
    }
  }

  // 非数字/动作活体
  if (config.livingbodyType !== 0 && config.livingbodyType !== 1) {
    var silentRecordTime = 4
    var cmsRecordTime = config.page.livingbody.silentRecordTime
    if (cmsRecordTime && typeof cmsRecordTime === 'number' && cmsRecordTime > 4) {
      silentRecordTime = cmsRecordTime
    }
    config.page.livingbody.silentRecordTime = silentRecordTime
  }

  // ocr 位置改动
  //cmsConfig.page.ocr.allowModifyType = '101';
  let tempArr = config.page.ocr.allowModifyType.split('')
  config.page.ocr.isIdnameAllowEdit = tempArr[0] === '0'
  config.page.ocr.isIdnumberAllowEdit = tempArr[1] === '0'
  config.page.ocr.isIdaddressAllowEdit = tempArr[2] === '0'
  console.log(config.page.ocr)

  return config
}

export default {
  init
}
